package com.cm.stock.manager.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

import com.cm.stock.manager.dto.ArticleDTO;

@Transactional
public class ArticleDAO {
	
	@PersistenceContext
	private EntityManager em;
	
	public ArticleDTO getByCode(String code){
		try{
			return (ArticleDTO) em.createQuery("select ar from ArticleDTO ar where ar.code=:code")
					.setParameter("code", code).getSingleResult();
		}catch (NoResultException e) {
			return null;
		}
		
	}
	
	public ArticleDTO getByDesignation (String designation){
		try{
			return (ArticleDTO) em.createQuery("select ar from ArticleDTO ar where ar.designation=:designation")
					.setParameter("designation", designation).getSingleResult();
		}catch (NoResultException e) {
			return null;
		}
		
	}
	
	public int getMaxId(){
		try{
			return (Integer) em.createQuery("select max(ar.id) from ArticleDTO ar ")
				.getSingleResult();
		}catch (Exception e) {
			return 0;
		}
		
	}
	
	public ArticleDTO save(ArticleDTO article){
		em.persist(article);
		return article;
	}
	
	public ArticleDTO update(ArticleDTO article){
		return em.merge(article);
	}
	
	@SuppressWarnings("unchecked")
	public List<ArticleDTO> getAll(){
		
		return em.createQuery("select ar from ArticleDTO ar").getResultList();
	}
	
	@SuppressWarnings("unchecked")
	public List<ArticleDTO> getByGroupe(String groupe){
		return  em.createQuery("select ar from ArticleDTO ar where ar.groupe=:groupe")
				.setParameter("groupe", groupe)
				.getResultList();
	}
	
	
public void deleteOne(Integer id) throws Exception {
		
	ArticleDTO article = em.find(ArticleDTO.class, id);
		if(article==null){
			throw new Exception("Article inexistant!");
		}
		em.remove(article);
	}
	

}
